package cn.schtwz.baselib.base

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import cn.schtwz.baselib.http.ApiException

import kotlinx.coroutines.TimeoutCancellationException
import java.lang.Exception

abstract class BaseViewModelActivity<B : ViewDataBinding> : BaseActivity<B>() {

    open abstract val viewModel: BaseViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        lifecycle.addObserver(viewModel)
        super.onCreate(savedInstanceState)
        startObserve()
    }

    private fun startObserve() {
        //处理一些通用异常，比如网络超时等
        viewModel.run {
            getError().observe(this@BaseViewModelActivity, Observer {
                requestError(it)
            })
            getFinally().observe(this@BaseViewModelActivity, Observer {
                requestFinally(it)
            })
        }
    }

    open fun requestFinally(it: Int?) {

    }

    open fun requestError(it: Exception?) {
        //处理一些已知异常
        it?.run {
            when (it) {
                is TimeoutCancellationException -> {
                    showToast("请求超时")
                }
                is ApiException -> {
                    showToast(it.localizedMessage)
                }
                else -> {
                    showToast("未知错误")
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(viewModel)
    }
}